/**
 * 作者：陈文斌 on 2019/1/7.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:crm/constant/api.dart';
import 'package:crm/tools/apollo_util.dart';
import 'package:crm/tools/http_util.dart';
import 'package:crm/model/Company/company_info_model.dart';
import 'package:crm/model/main_scoped_model.dart';
import 'package:crm/model/ClientManager/client_info_model.dart';
import 'package:crm/model/ClientManager/contact_info_model.dart';
import 'package:crm/view/Dialog/loading_dialog.dart';

class ClientManagerVM {
  /// 获取客户列表
  getListData(
    int page,
    List<ClientInfoModel> clientsInfo, {
    int customerType,
    Function callback,
    Function errorCallback,
  }) async {
    final int _take = 10; // 每次请求10条信息
    final int _skip = page * _take; // 从第skip + 1条开始请求
    bool _isMore = true;

    Map args = {
      'skip': '${_skip}',
      'take': '$_take',
      'customerType': customerType,
      'timeType': -1,
    };


    ApolloRequestUtil.customersSearch(
      (response) {
        // 请求成功回调
        var _result = response['data']['customersAll']['items'];
        if (page == 0) clientsInfo = List<ClientInfoModel>();
        for (var newsItem in _result) {
          clientsInfo.add(ClientInfoModel.fromJson(newsItem));
        }

        _isMore = _result.length == _take;

        if (callback != null) {
          callback(clientsInfo, _isMore);
        }
      },
      args: args,
      errorCallback: (errMsg) {
        // 请求失败
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  /// 添加客户、潜在客户
  addClient(
    BuildContext context, {
    ClientInfoModel client,
    int customerType,
    List<ContactInfoModel> contacts,
  }) {
    bool _isSave = true;
    if (client.companyName == null || client.companyName.length == 0) {
      _isSave = false;
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Text(
              '请输入公司名称',
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
    }

    if (_isSave) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return LoadingDialog();
        },
      );

      List<Map> contactsList = List<Map>();
      contacts.forEach((ContactInfoModel contact) {
        Map _contactMap = {
          "name": contact.name,
          "position": contact.position,
          "phone": contact.phone,
          "telephone": contact.telephone,
          "QQaccount": contact.QQaccount,
          "mail": contact.telephone,
        };
        if (contact.employeeId != null) {
          _contactMap["employeeId"] = contact.employeeId;
        }
        contactsList.add(_contactMap);
      });

      Map args = {
        "companyName": client.companyName,
        "industryClassification": client.industryClassification,
        "phone": client.phone,
        "location": client.location,
        "streetaddress": client.streetaddress,
        "customerType": customerType,
        "contactsList": contactsList,
      };

      ApolloRequestUtil.customerAOU(
        (response) {
          /// 去除请求动画
          Navigator.pop(context);

          /// 返回上级界面
          Navigator.pop(context);
        },
        args: args,
        errorCallback: (errMsg) {
          /// 去除请求动画
          Navigator.pop(context);
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return ErrorDialog(
                text: '添加失败，请重试！',
              );
            },
          );

          /// 延迟3秒去除失败提示
          Future.delayed(Duration(seconds: 3), () => Navigator.pop(context));
        },
      );
    }
  }

  /// 添加联系人
  saveContactsInfo(BuildContext context, List<ContactInfoModel> contacts) {
    bool _isSave = true;
    for (int i = 0; i < contacts.length; i++) {
      ContactInfoModel _contact = contacts[i];
      if (_contact.name == null || _contact.name.length == 0) {
        _isSave = false;
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content: Text(
                '请输入"联系人${i + 1}"的姓名',
              ),
              actions: <Widget>[
                FlatButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        );
        break;
      } else if (_contact.phone == null || _contact.phone.length == 0) {
        _isSave = false;
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content: Text(
                '请输入"联系人${i + 1}"的手机',
              ),
              actions: <Widget>[
                FlatButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        );
        break;
      }
    }
    if (_isSave) {
      MainModel().of(context).addContactAll(contacts);
      Navigator.pop(context);
    }
  }

  /// 获取客户列表
  getCompany(
      int page,
      List<CompanyInfoModel> companies, {
        String keyword,
        Function callback,
        Function errorCallback,
      }) async {
    final int _take = 10; // 每次请求10条信息
    final int _skip = page * _take; // 从第skip + 1条开始请求
    bool _isMore = true;

    Map<String, String> data = {
      'Skip': '${_skip}',
      'Take': '$_take',
    };

    if(keyword != null && keyword.isNotEmpty){
      data['Keyword'] = keyword;
    }

    HttpUtil.get(
      Api.CompaniesByKeyword,
          (response) {
        // 请求成功回调
        var _result = response;
        if (page == 0) companies = List<CompanyInfoModel>();
        for (var compony in _result) {
          companies.add(CompanyInfoModel.fromJson(compony));
        }

        _isMore = _result.length == _take;

        if (callback != null) {
          callback(companies, _isMore);
        }
      },
      params: data,
      errorCallback: (errMsg) {
        // 请求失败
        if (errorCallback != null) {
          errorCallback(errMsg);
        }
      },
    );
  }

  static String getSubTitle(CompanyInfoModel client) {
    String _subTitle = '';
    if (client.ResidentProvince != null) {
      _subTitle = '${client.ResidentProvince}.${client.CustomIndustryCategories ?? ''}';
    } else {
      _subTitle = '${client.CustomIndustryCategories ?? ''}';
    }

    return _subTitle;
  }

  static int getVerifyStatus(CompanyInfoModel client){
    // 0：商户、1：企业、2：个体
    int type = 0;
    if (!client.NotAllPass) {
      type = 1;
    } else if (client.IsIndividual) {
      type = 2;
    }

    return type;
  }
}
